#coding=utf-8

def str2Int(val_str, def_val=None):
    try:
        return int(val_str)
    except:
        return def_val

def myStr(val):
    if not(isinstance(val, str) or isinstance(val, unicode)):
        return str(val) #if abs(val) > 0.001 else "0"
    return val

def toStr(val):
    if isinstance(val, float):
        if abs(val) > 10000:
            val = '%.2f' %val
            val = val.rstrip('0')
            val = val.rstrip('.')
        else:
            val = '%g' %val
    
    if (type(val) != str and type(val) != unicode):
        val = str(val)

    return val

def getRootWin(win):
    while(win.GetParent()):
        win = win.GetParent()
    return win

def getWxDate(date):
    import wx
    import datetime
    
    if date is None:
        date = datetime.date.today()
    return wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0)

def str2Date(dateStr):
    import datetime
    import time
    return datetime.datetime(*(time.strptime(dateStr,'%Y-%m-%d')[0:6])).date()

def str2DateTime(dateStr, hourStr, minStr, secStr):
    import datetime
    import time
    new_str = dateStr+" "+hourStr+":"+minStr+":"+secStr
    #return datetime.datetime(*(time.strptime(dateStr,'%Y-%m-%d %H:%M')[0:12])).date()
    return datetime.datetime.strptime(new_str,'%Y-%m-%d %H:%M:%S')
    
def myFloat(val):
    import decimal
    return decimal.Decimal(str(val))

def myFloat2(str):
    try:
        val = float(str)
    except ValueError as error:
        msg = u'发生错误：%s' %error
        dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
        dlg.ShowModal()
        
    return val

def toFloatOrZero(val):
    return float(val or "0")

def myFloatStrTest(str):
    try:
        val = float(str)
    except ValueError as error:
        msg = u'发生错误：%s' %error
        dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
        dlg.ShowModal()
        return False
    return True
        
def exportList(lc, file):
    import xlwt
    
    try:
        wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)  
        sheet = wbk.add_sheet('sheet 1', cell_overwrite_ok=True)
    
        for col in range(lc.GetColumnCount()):
            sheet.write(0, col, lc.GetColumn(col).GetText()) 
            
        for row in range(lc.GetItemCount()):
            for col in range(lc.GetColumnCount()):            
                sheet.write(row+1, col, lc.GetItem(row, col).GetText()) 
          
        wbk.save(file)
        return 0
    
    except Exception,e:
        import traceback
        traceback.print_exc()
        print e
        return -1
    
def exportSelect(data, file, bSale = True):
    import xlwt
    
    try:
        wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)  
        sheet = wbk.add_sheet('Sheet0', cell_overwrite_ok=False)
        #sheet = wbk.get_sheet(1) #读不到

        col = []
        col.append(u'录单时间')
        #col.append(u'交货时间')
        col.append(u'订货客户' if bSale else u'供应商')
        col.append(u'客户名称')
        #col.append(u'发货仓库')
        col.append(u'经手人')
        #col.append(u'部门')
        #col.append(u'结算单位')
        col.append(u'单据备注')
        col.append(u'抹零金额')# 1、同一张单据的抹零金额必须相等 2、抹零金额包含全部优惠
        #col.append(u'赠品') # 请录入：是、否其他信息无法识别，为空时，默认处理为否
        col.append(u'商品ID')
        col.append(u'商品编号')
        #col.append(u'商品条码')
        col.append(u'商品')
        #col.append(u'商品规格')
        #col.append(u'明细仓库')
        col.append(u'单位')
        col.append(u'数量')
        #col.append(u'副单位数量')
        col.append(u'单价')
        #col.append(u'金额')
        #col.append(u'折扣 (%)')
        #col.append(u'折后单价')
        #col.append(u'折后金额')
        col.append(u'明细备注')

        col.append(u'发货仓库'if bSale else u'入库仓库')
        col.append(u'部门')

        for iCol,title in enumerate(col):
            sheet.write(0, iCol, title)
    
        for iRow,row in enumerate(data):
            for iCol,content in enumerate(row):
                sheet.write(iRow+1, iCol, content)
          
        wbk.save(file)
        return 0
    
    except Exception,e:
        import traceback
        traceback.print_exc()
        print e
        return -1
    
def concat(list, separator):
        str = ''
        for i in range(len(list)):
            str += '%s%s' %(myStr(list[i]), separator)
            
        iEnd = -len(separator)
    
        return str[:iEnd]

def OnActivate(event):
##        if (event.GetActive()):
##            win = event.GetEventObject()
##            print '%s %d' %(win.GetTitle(),win.IsIconized())
##            parent = win.GetParent()
##            if (parent.IsIconized() and win.IsIconized()):
##                print 'showWithChild'
##                parent.showWithChild()
        event.Skip()
        
def conShow(wxChild):
    import wx    
    wxChild.Bind(wx.EVT_ACTIVATE, OnActivate)

def showModal(info, quest=False):
    import wx
    
    if quest:
        style = wx.YES_NO|wx.ICON_QUESTION
    else:
        style = wx.OK|wx.ICON_INFORMATION
        
    dlg = wx.MessageDialog(None, info, u'消息框',style)
    return dlg.ShowModal()
 

   
def showExcept(e, info=''):
    import wx
    msg = u'发生异常：%s\ninfo:%s' %(e, info)
    print msg
    try:
        dlg = wx.MessageDialog(None, msg,u'提示',wx.OK|wx.ICON_ERROR)
        dlg.ShowModal()
    except Exception,exp:
        print exp
        
def trace(fmt='', param=None):
    import sys
    
    #print type(param)
    str = '[%s:%s:%d]'%(sys._getframe().f_back.f_code.co_filename,
                            sys._getframe().f_back.f_code.co_name,
                            sys._getframe().f_back.f_lineno)
    if fmt:
        str += fmt
        if param is not None:
            if(type(param) is list):         
                str =str %tuple(param)
            else:
                str =str %param
    print str